package wedaex.content;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.commons.lang.ArrayUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.builder.ToStringBuilder;
import org.apache.commons.lang.builder.ToStringStyle;
import org.w3c.dom.Document;
import org.w3c.dom.Element;

@SuppressWarnings("serial")
public class RegExpContentExtractor extends ContentExtractorBase implements ContentExtractor {
	private Pattern pattern;
	private boolean trimNewLine;
	private int[] contentPos;
	public RegExpContentExtractor(String name, ContentSource contentSource, String pattern, boolean trimNewLine, int[] contentPos) {
		super(name, contentSource);
		this.pattern = Pattern.compile(pattern, Pattern.DOTALL);
		this.trimNewLine = trimNewLine;
		this.contentPos = contentPos;
	}

	public String extract() throws Exception {
		Page page = contentSource.retrieveContent();
		String contentToMatch = trimNewLine ?
				StringUtils.replace(page.getContent(), "\n", " ") : page.getContent();

		String[] lines = StringUtils.split(contentToMatch, "\n");
		for (String line : lines) {
			Matcher m = pattern.matcher(line);
			if(!m.find()) continue;
			
			StringBuilder sb = new StringBuilder();
			for (int i = 0; i < contentPos.length; i++) {
				sb.append(m.group(contentPos[i]));
			}
			return sb.toString();
		}
		return null;
	}
	
	public String toString() {
		return new ToStringBuilder(this, ToStringStyle.SHORT_PREFIX_STYLE)
				.append("name", name)
				.append("contentSource", contentSource)
				.append("pattern", pattern)
				.append("trimNewLine", trimNewLine)
				.append("contentPos", contentPos)
				.toString();
	}

	public Element toXml(Document doc) {
		// extractor tag
		Element extractor = doc.createElement("extractor");
		extractor.setAttribute("type", "regExpExtractor");
		extractor.setAttribute("name", this.name);
		extractor.setAttribute("trimNewLine", trimNewLine?"true":"false");
		extractor.setAttribute("contentPositions", StringUtils.join(ArrayUtils.toObject(contentPos), ","));
		
		// pattern tag
		Element pattern = doc.createElement("pattern");
		pattern.appendChild(doc.createCDATASection(this.pattern.toString()));
		extractor.appendChild(pattern);
		
		// source tag 
		extractor.appendChild(this.contentSource.toXml(doc));

		return extractor;
	}
}
